<template>
  <div class="search-form">
    <div class="search-content">
      <el-form :label-width="$attrs['label-width']?$attrs['label-width']:'auto'"
               :inline="true"
               :rules="rules"
               :model="ruleForm"
               ref="ruleForm"
               :class="$attrs['clo-width']?'flex justify-between flex-wrap demo-form-inline':'demo-form-inline'">
        <template slot-scope
                  v-for="(item, index) in searchList ">
          <el-form-item v-if="item.type!=='length-width-height'&&!item.type.includes('selectInput')&&(item.isShow!==undefined?item.isShow:true)"
                        :key="index"
                        :required="item.required"
                        :label="labelName(item.label)"
                        :label-width="item.labelWidth ? item.labelWidth : null"
                        :prop="item.prop?item.prop:null">
            <el-input v-if="item.type === 'input'"
                      size="small"
                      v-model="ruleForm[item.name]"
                      clearable
                      :type="item.inputType?item.inputType:'text'"
                      :disabled="item.disabled?item.disabled:false"
                      :readonly="item.readonly?item.readonly:false"
                      :placeholder="item.placeholder?placeholder('input',item.placeholder):null"
                      :min="item.min?item.min:defaultNumber"
                      :max="item.max?item.max:null"
                      @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item):null"
                      @focus="item.focus&&(Object.prototype.toString.call(item.focus)==='[object Function]')?item.focus($event,item):null"
                      @blur="item.blur&&(Object.prototype.toString.call(item.blur)==='[object Function]')?item.blur($event,item):null"></el-input>
            <span class="margin-left-sm"
                  v-if="item.type === 'input'&&item.unitText!==undefined">{{item.unitText}}</span>

            <el-input v-if="item.type === 'textarea'"
                      size="small"
                      :autosize="{ minRows: item.options&&item.options.minRows?item.options.minRows:1, maxRows: item.options&&item.options.maxRows?item.options.maxRows:4}"
                      v-model="ruleForm[item.name]"
                      clearable
                      :disabled="item.disabled?item.disabled:false"
                      :readonly="item.readonly?item.readonly:false"
                      type="textarea"
                      :maxlength="item.options&&item.options.maxlength?item.options.maxlength:null"
                      show-word-limit
                      :placeholder="item.placeholder?placeholder('input',item.placeholder):null"></el-input>
            <el-select v-if="item.type === 'select'"
                       size="small"
                       v-model="ruleForm[item.name]"
                       :multiple="item.multiple!==undefined?item.multiple:false"
                       :disabled="item.disabled?item.disabled:false"
                       :placeholder="item.placeholder?placeholder('select',item.placeholder):null"
                       v-loading="item.loading!==undefined&&item.loading?true:false"
                       :allow-create="item.allowCreate!==undefined?item.allowCreate:false"
                       :filterable="item.allowCreate!==undefined||item.filterable!==undefined?item.allowCreate||item.filterable:false"
                       default-first-option
                       :data-aloo="item.allowCreate"
                       :autocomplete="item.autocomplete===undefined?'new-password':item.autocomplete"
                       clearable
                       @focus="item.focus&&(Object.prototype.toString.call(item.focus)==='[object Function]')?item.focus($event,item):null"
                       @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item):null">
              <el-option v-for="(item1,index1) in item.selectOptions"
                         :key="index1"
                         :label="labelName(item1.label)"
                         :value="item1.value"></el-option>
            </el-select>
            <el-radio-group v-if="item.type === 'radio'"
                            size="small"
                            v-model="ruleForm[item.name]"
                            :disabled="item.disabled?item.disabled:false"
                            @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item):null">
              <el-radio v-for="(item1,index1) in item.selectOptions"
                        :key="index1"
                        :label="item1.value">{{labelName(item1.label)}}</el-radio>
            </el-radio-group>
            <el-checkbox-group v-if="item.type === 'checkbox'"
                               size="small"
                               v-model="ruleForm[item.name]"
                               :disabled="item.disabled?item.disabled:false">
              <el-checkbox v-for="(item1,index1) in item.selectOptions"
                           :key="index1"
                           :label="item1.value">{{labelName(item1.label)}}</el-checkbox>
            </el-checkbox-group>
            <el-date-picker v-if="item.type === 'daterange'"
                            size="small"
                            v-model="ruleForm[item.name]"
                            type="daterange"
                            range-separator="-"
                            :start-placeholder="$t('el.datepicker.startDate')"
                            :end-placeholder="$t('el.datepicker.endDate')"
                            :disabled="item.disabled?item.disabled:false"
                            :format="item.format!==undefined?item.format:null"
                            :value-format="item.valueFormat!==undefined?item.valueFormat:null"
                            :default-time="item.defaultTime!==undefined?item.defaultTime:null" />
            <el-date-picker v-if="item.type === 'date'"
                            v-model="ruleForm[item.name]"
                            size="small"
                            type="date"
                            :placeholder="$t('el.datepicker.selectDate')"></el-date-picker>
            <el-date-picker v-if="item.type === 'datetime'"
                            size="small"
                            v-model="ruleForm[item.name]"
                            type="datetime"
                            :placeholder="$t('el.datepicker.selectDate')"></el-date-picker>
            <el-date-picker v-if="item.type === 'datetimerange'"
                            size="small"
                            v-model="ruleForm[item.name]"
                            type="datetimerange"
                            :placeholder="$t('el.datepicker.selectDate')"></el-date-picker>
          </el-form-item>
        </template>

        <el-form-item v-if="operation.submitState||operation.reset">
          <el-button v-if="operation.submitState"
                     type="primary"
                     size="small"
                     icon="el-icon-search"
                     @click="onSubmit">{{$t('i18n_search')}}</el-button>
          <el-button v-if="operation.reset"
                     type="primary"
                     plain
                     size="small"
                     @click="resetForm">{{$t('i18n_reset')}}</el-button>

        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import Cookies from 'js-cookie'
export default {
  data() {
    return {
      ruleForm: {},
      ruleFormData: {}
    }
  },
  props: {
    searchList: {
      type: Array,
      default: function () {
        return []
      }
    },
    defaultNumber: {
      type: Number,
      default: 0
    },
    operation: {
      type: Object,
      default: function () {
        return {
          submitState: true,
          reset: true
        }
      }
    },
    rules: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  computed: {

  },
  watch: {

  },
  created() {

  },
  mounted() {
  },
  destroyed() { //
    this.resetForm()
  },
  methods: {
    changeOption(val, item) {
      this.searchList.map((v) => {
        if (item.changeTo === v.name) {
          if (val) {
            v[item.changeOptions.opt] = !item.changeOptions.value
          } else {
            v[item.changeOptions.opt] = item.changeOptions.value
          }
        }
      })
    },
    placeholder(type, data) {
      if (data.indexOf('.') !== -1) {
        if (type === 'select') {
          return data ? (this.$t('el.select.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('el.select.placeholder')
        }
        if (type === 'input') {
          return data ? (this.$t('input.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('input.placeholder')
        }
        if (type === 'daterange' || type === 'date') {
          return data ? (this.$t('input.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('input.placeholder')
        }
      } else if (data.indexOf('i18n') !== -1) {
        const str = this.$utils.getLabelName(data, this)
        if (Cookies.get('lang') === 'en') {
          if (type === 'select') {
            return this.$t('el.select.placeholder') + ' ' + str
          }
          if (type === 'input') {
            return this.$t('input.placeholder') + ' ' + str
          }
          if (type === 'select') {
            return this.$t('el.select.placeholder') + ' ' + str
          }
        } else {
          if (type === 'select') {
            return this.$t('el.select.placeholder') + str
          }
          if (type === 'input') {
            return this.$t('input.placeholder') + str
          }
          if (type === 'select') {
            return this.$t('el.select.placeholder') + str
          }
        }
      } else {
        return data
      }
    },
    labelName(data) { // 多语言切换
      if (data !== undefined) {
        if (data.indexOf('.') !== -1) {
          return this.$t(data)
        } else if (data.indexOf('i18n') !== -1) {
          return this.$utils.getLabelName(data, this)
        } else {
          return data
        }
      } else {
        return ''
      }
    },
    onSubmit() {
      const ruleForm = _.clone(this.ruleForm)
      ruleForm.pageIndex = 1
      const dateTwins = []
      const datetimes = []
      this.searchList.map(item => {
        if (item.type === 'daterange') {
          dateTwins.push(item)
        }
        if (item.type === 'datetimerange') {
          datetimes.push(item)
        }
        if (item.type === 'date' || item.type === 'datetime') {
          ruleForm[item.name] = ruleForm[item.name]
            ? this.$utils.formatDateTime(ruleForm[item.name])
            : ''
        }
      })
      if (dateTwins.length > 0) {
        dateTwins.map(item => {
          Object.keys(item).forEach(key => {
            if (key === 'name') {
              const nameOptions = item[key].split('-')
              if (nameOptions.length > 0) {
                nameOptions.forEach((item2, index) => {
                  ruleForm[item2] = ''
                  if (ruleForm[item[key]] && ruleForm[item[key]][index]) {
                    ruleForm[item2] = this.$utils.formatDateTime(ruleForm[item[key]][index])
                  }
                })
                delete ruleForm[item[key]]
              }
            }
          })
        })
      }
      if (datetimes.length > 0) {
        datetimes.map(item => {
          Object.keys(item).forEach(key => {
            if (key === 'name') {
              const nameOptions = item[key].split('-')
              if (nameOptions.length > 0) {
                nameOptions.forEach((item2, index) => {
                  ruleForm[item2] = ''
                  if (ruleForm[item[key]] && ruleForm[item[key]][index]) {
                    ruleForm[item2] = this.$utils.formatDateTime(ruleForm[item[key]][index])
                  }
                })
                delete ruleForm[item[key]]
              }
            }
          })
        })
      }
      if (JSON.stringify(this.rules) !== '{}') {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.$emit('searchSubmit', ruleForm)
            this.ruleFormData = ruleForm
          } else {
            return false
          }
        })
      } else {
        this.ruleFormData = ruleForm
        this.$emit('searchSubmit', ruleForm)
      }
    },
    submit() { // 暴露给外面调用
      this.onSubmit()
      let flag = true
      if (JSON.stringify(this.rules) !== '{}') {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            flag = true
          } else {
            flag = false
          }
        })
      }
      if (flag === true) {
        return this.ruleFormData
      }
    },
    resetForm() {
      this.searchList.map((item) => {
        item.value = ''
      })
      Object.keys(this.ruleForm).forEach(key => {
        this.ruleForm[key] = ''
      })
      this.$emit('resetForm')
    }

  }

}

</script>

<style lang="scss" scoped>
@import '~@styles/variable.scss';
.search-form {
  .search-title {
    font-size: 18px;
    margin-bottom: 20px;
  }
  .demo-form-inline {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  .el-form {
    &/deep/ .el-form-item {
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      height: 42px;
      &.ies-select-input {
        .el-form-item__content {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .el-form-item {
            .el-form-item__content {
              height: 40px;
            }
          }
        }
      }
      .el-form-item__label {
        white-space: nowrap;
      }
    }
  }
}
</style>
